import React, { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { Input, Select, Button, Table, Tag, Space, message } from 'antd';
import { SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import './ReleasesPage.css';
import { releaseApi, projectGroupApi } from '../../services/api';
import { useKeycloak } from '../../contexts/KeycloakContext';

const ReleasesPage = () => {
  const navigate = useNavigate();
  const { keycloak, user } = useKeycloak();
  
  // 状态定义
  const [releases, setReleases] = useState([]);
  const [loading, setLoading] = useState(true);
  const [filters, setFilters] = useState({
    releaseName: '',
    envType: '',
    projectGroupId: '',
    namespace: ''
  });
  const [projectGroups, setProjectGroups] = useState([]);
  const [envTypes] = useState([
    { value: 'dev', label: '开发环境' },
    { value: 'test', label: '测试环境' },
    { value: 'staging', label: '预发环境' },
    { value: 'prod', label: '生产环境' }
  ]);
  const [pageReady, setPageReady] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total) => `共 ${total} 条`
  });

  // 页面准备就绪状态
  useEffect(() => {
    console.log('检查页面准备状态，keycloak.authenticated:', keycloak.authenticated, 'user:', user);
    
    const checkAuthStatus = async () => {
      // 如果存在用户信息，直接设置页面就绪
      if (user && user.id) {
        console.log('用户信息存在，用户ID:', user.id);
        setPageReady(true);
        return;
      }
      
      // 如果 Keycloak 已认证
      if (keycloak.authenticated) {
        // 尝试加载用户信息
        console.log('Keycloak 已认证，尝试加载用户信息...');
        try {
          const profile = await keycloak.loadUserProfile();
          console.log('用户信息加载成功:', profile);
          // 用户信息会通过 KeycloakContext 自动更新
          setPageReady(true);
        } catch (error) {
          console.error('加载用户信息失败:', error);
          // 即使用户信息加载失败，也继续加载页面
          setPageReady(true);
        }
      } else if (keycloak.initialized && !keycloak.authenticated) {
        // 如果 Keycloak 已初始化但未认证，重定向到登录页
        console.log('用户未认证，重定向到登录页');
        navigate('/login', { state: { from: window.location.pathname } });
      } else {
        // 如果 keycloak 状态不明确但我们已经到达这个页面，假设用户已经通过认证
        console.log('Keycloak 状态不明确，假设用户已认证');
        setPageReady(true);
      }
    };
    
    checkAuthStatus();
  }, [user, keycloak, navigate]);
  
  // 获取项目组列表
  const fetchProjectGroups = useCallback(async () => {
    try {
      const response = await projectGroupApi.getProjectGroups(1, 100);
      if (response && response.code === 200 && response.data) {
        const groups = response.data.records.map(group => ({
          value: group.id,
          label: group.groupName
        }));
        setProjectGroups([{ value: '', label: '全部' }, ...groups]);
        return true;
      } else {
        message.error(response?.message || '获取项目组列表失败');
        return false;
      }
    } catch (error) {
      console.error('获取项目组列表异常:', error);
      message.error('获取项目组列表失败: ' + (error.message || '未知错误'));
      return false;
    }
  }, []);
  
  // 加载发布列表数据
  const fetchReleases = useCallback(async () => {
    console.log('fetchReleases called, pageReady:', pageReady, '时间:', new Date().toISOString());
    if (!pageReady) return;
    
    try {
      setLoading(true);
      
      const params = {
        page: pagination.current,
        size: pagination.pageSize,
        releaseName: filters.releaseName || undefined,
        envType: filters.envType || undefined,
        projectGroupId: filters.projectGroupId || undefined,
        namespace: filters.namespace || undefined,
        // 添加随机参数避免缓存
        _t: new Date().getTime()
      };
      
      console.log('调用/release/page接口，参数:', params);
      const response = await releaseApi.getReleases(
        params.page,
        params.size,
        undefined, // projectId
        undefined, // moduleId
        params.envType,
        undefined, // clusterId
        params.namespace,
        params.releaseName,
        params.projectGroupId
      );
      
      console.log('Release列表响应:', response);
      if (response && response.code === 200 && response.data) {
        setReleases(response.data.records || []);
        setPagination(prev => ({
          ...prev,
          total: response.data.total || 0
        }));
      } else {
        message.error(response?.message || '获取发布列表失败');
        setReleases([]);
      }
    } catch (error) {
      console.error('获取发布列表异常:', error);
      message.error('获取发布列表失败: ' + (error.message || '未知错误'));
      setReleases([]);
    } finally {
      setLoading(false);
    }
  }, [pageReady, pagination.current, pagination.pageSize, filters]);
  
  // 初始化加载数据
  useEffect(() => {
    if (pageReady) {
      console.log('页面准备就绪，开始加载数据...');
      const loadData = async () => {
        try {
          console.log('加载项目组数据...');
          const groupsLoaded = await fetchProjectGroups();
          
          if (groupsLoaded) {
            console.log('加载发布列表数据...');
            await fetchReleases();
          }
        } catch (error) {
          console.error('加载数据失败:', error);
          message.error('加载数据失败: ' + (error.message || '未知错误'));
        }
      };
      
      loadData();
    }
  }, [pageReady, fetchProjectGroups, fetchReleases]);


  
  // 当分页或筛选条件变化时重新加载数据
  useEffect(() => {
    if (pageReady) {
      console.log('Filters or pagination changed, reloading data...');
      fetchReleases();
    }
  }, [pagination.current, pagination.pageSize, filters, pageReady, fetchReleases]);
  
  // 处理表格分页、排序、筛选变化
  const handleTableChange = (pagination, filters, sorter) => {
    setPagination({
      ...pagination,
      current: pagination.current
    });
  };
  
  // 处理筛选条件变化
  const handleFilterChange = (key, value) => {
    setFilters(prev => ({
      ...prev,
      [key]: value
    }));
  };
  
  // 处理搜索
  const handleSearch = () => {
    // 重置到第一页
    setPagination(prev => ({
      ...prev,
      current: 1
    }));
    fetchReleases();
  };
  
  // 重置筛选条件
  const resetFilters = () => {
    setFilters({
      releaseName: '',
      envType: '',
      projectGroupId: '',
      namespace: ''
    });
    // 重置到第一页并重新加载数据
    setPagination(prev => ({
      ...prev,
      current: 1
    }));
    // 重置后立即获取数据
    fetchReleases();
  };
  
  // 表格列定义
  const columns = [
    {
      title: '序号',
      key: 'index',
      width: 80,
      render: (_, __, index) => (pagination.current - 1) * pagination.pageSize + index + 1,
    },
    {
      title: 'Release名称',
      dataIndex: 'releaseName',
      key: 'releaseName',
      ellipsis: true,
      render: (text, record) => (
        <Button 
          type="link" 
          style={{ padding: 0, height: 'auto' }}
          onClick={() => handleViewDetail(record)}
        >
          {text}
        </Button>
      ),
    },
    {
      title: 'Chart',
      dataIndex: 'chartName',
      key: 'chartName',
      ellipsis: true,
    },
    {
      title: 'Revision',
      dataIndex: 'revision',
      key: 'revision',
      width: 100,
    },
    {
      title: '环境/命名空间',
      key: 'envNamespace',
      render: (_, record) => (
        <Space direction="vertical" size={4}>
          {record.envType && <Tag color={getEnvColor(record.envType)}>{record.envType}</Tag>}
          {record.namespace && <span>{record.namespace}</span>}
        </Space>
      ),
    },
    {
      title: '镜像',
      dataIndex: 'image',
      key: 'image',
      ellipsis: true,
    },
    {
      title: '项目',
      dataIndex: 'projectName',
      key: 'projectName',
      ellipsis: true,
    },
    {
      title: '项目组',
      dataIndex: 'projectGroupName',
      key: 'projectGroupName',
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size="middle">
          <Button type="link" size="small" onClick={() => handleViewDetail(record)}>详情</Button>
          <Button type="link" size="small" onClick={() => handleEdit(record)}>编辑</Button>
          <Button type="link" danger size="small" onClick={() => handleDelete(record)}>删除</Button>
        </Space>
      ),
    },
  ];

  // 获取环境标签颜色
  const getEnvColor = (env) => {
    const colors = {
      'dev': 'blue',
      'test': 'orange',
      'staging': 'purple',
      'prod': 'red',
    };
    return colors[env] || 'default';
  };

  // 查看详情
  const handleViewDetail = (record) => {
    console.log('查看详情:', record);
    // 跳转到版本详情页
    navigate(`/project/${record.projectId}/version/${record.id}`);
  };

  // 编辑
  const handleEdit = (record) => {
    console.log('编辑:', record);
    // 这里可以跳转到编辑页或显示编辑弹窗
  };

  // 删除
  const handleDelete = async (record) => {
    console.log('删除:', record);
    // 这里可以添加删除确认和删除逻辑
  };

  return (
    <div className="releases-page">
      <div className="releases-header">
        <h1>发布管理</h1>
      </div>
      
      <div className="releases-filters">
        <div className="filter-row">
          <div className="filter-item">
            <label>Release名称:</label>
            <Input 
              placeholder="请输入Release名称" 
              value={filters.releaseName}
              onChange={(e) => handleFilterChange('releaseName', e.target.value)}
              allowClear
            />
          </div>
          
          <div className="filter-item">
            <label>环境:</label>
            <Select
              placeholder="请选择环境"
              style={{ width: '100%' }}
              value={filters.envType || undefined}
              onChange={(value) => handleFilterChange('envType', value)}
              allowClear
            >
              {envTypes.map(env => (
                <Select.Option key={env.value} value={env.value}>
                  {env.label}
                </Select.Option>
              ))}
            </Select>
          </div>
          
          <div className="filter-item">
            <label>项目组:</label>
            <Select
              placeholder="请选择项目组"
              style={{ width: '100%' }}
              value={filters.projectGroupId || undefined}
              onChange={(value) => handleFilterChange('projectGroupId', value)}
              allowClear
              loading={loading}
            >
              {projectGroups.map(group => (
                <Select.Option key={group.value} value={group.value}>
                  {group.label}
                </Select.Option>
              ))}
            </Select>
          </div>
          
          <div className="filter-item">
            <label>命名空间:</label>
            <Input 
              placeholder="请输入命名空间" 
              value={filters.namespace}
              onChange={(e) => handleFilterChange('namespace', e.target.value)}
              allowClear
            />
          </div>
        </div>
      </div>
      
      <div className="releases-actions">
        <Space>
          <Button 
            type="primary" 
            icon={<SearchOutlined />} 
            onClick={handleSearch}
            loading={loading}
          >
            搜索
          </Button>
          <Button 
            icon={<ReloadOutlined />} 
            onClick={resetFilters}
            disabled={loading}
          >
            重置
          </Button>
        </Space>
      </div>
      
      <div className="releases-table">
        <Table
          columns={columns}
          dataSource={releases}
          rowKey="id"
          loading={loading}
          pagination={pagination}
          onChange={handleTableChange}
          scroll={{ x: 'max-content' }}
        />
      </div>
    </div>
  );
};

export default ReleasesPage;
